package com.ys.controller.api.account;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.bo.dto.NameValueDto;
import com.ys.service.flow.YspTaskService;
import com.ys.service.sys.PdfService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.ys.config.MenuId;
import com.ys.entity.account.TcwNeedPayAccountPay;
import com.ys.entity.account.TcwNeedPayAccountPayItem;
import com.ys.entity.sys.YsCol;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.account.TcwNeedPayAccountPayService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/api/inter/tcwNeedPayAccountPay")
public class ApiInterTcwNeedPayAccountPayController {
	
	@Autowired
	private CommonApiService<TcwNeedPayAccountPay> commonApiService;
	@Autowired
	private CommonApiService<TcwNeedPayAccountPayItem> commonApiServiceItem;

	@Autowired
	private YspTaskService yspTaskService;

	@Autowired
	private TcwNeedPayAccountPayService tcwNeedPayAccountPayService;

	@Autowired
	private PdfService pdfService;
	
	@RequiresPermissions("tcwNeedPayAccountPay:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcwNeedPayAccountPayItem cond){
		
		cond = setSeachSql(cond);
		
		cond.setOrderby("A.Id DESC");
		
		return commonApiServiceItem.searchLay(cond);
	}
	
	/**
	 * 新增
	 */
	@RequestMapping("/add")
	@ResponseBody
	@RequiresPermissions("tcwNeedPayAccountPay:add")
	public R add(String bid, String needPayAccountCode, String companyBankInfoVid, String remark, String subData,int payStatus) {
		try {
			return tcwNeedPayAccountPayService.add(bid, needPayAccountCode, companyBankInfoVid, remark, subData, MenuId.TCW_NeedPayAccountPay, payStatus);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}

	/**
	 * 编辑
	 */
	@RequiresPermissions("tcwNeedPayAccountPay:add")
	@PostMapping("/edit")
    @ResponseBody
	public R edit(String bid, String needPayAccountCode, String companyBankInfoVid, String remark, String annexFile, String subData,int payStatus){
		try {
			return tcwNeedPayAccountPayService.edit(bid, needPayAccountCode, companyBankInfoVid, remark, annexFile, subData, MenuId.TCW_NeedPayAccountPay, payStatus);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("系统正在开小差，请联系客服，我们将第一时间为您解决！");
		}
	}
	
	/**
	 * 流转通过
	 */
	@RequiresPermissions("tcwNeedPayAccountPay:add")
	@PostMapping("/flowPass")
    @ResponseBody
	public R flowPass(HttpServletRequest request, Long id){
		TcwNeedPayAccountPay tcwNeedPayAccountPay = new TcwNeedPayAccountPay().setId(id).queryFirst();
		try {
			return tcwNeedPayAccountPayService.flowPass(tcwNeedPayAccountPay.getBid(), ShiroUtils.getUserId());
		} catch (IllegalArgumentException e) {
			return R.error(e.getMessage());
		}catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcwNeedPayAccountPay:add")
	@PostMapping("/flowRefuse")
    @ResponseBody
	public R flowRefuse(HttpServletRequest request, Long id, String reason){
		TcwNeedPayAccountPay tcwNeedPayAccountPay = new TcwNeedPayAccountPay().setId(id).queryFirst();
		try {
			return tcwNeedPayAccountPayService.flowRefuse(tcwNeedPayAccountPay.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}


	/**
	 * 流转驳回
	 */
	@RequiresPermissions("tcwNeedPayAccountPay:add")
	@PostMapping("/flowInit")
	@ResponseBody
	public R flowInit(HttpServletRequest request, Long id, String reason){
		TcwNeedPayAccountPay tcwNeedPayAccountPay = new TcwNeedPayAccountPay().setId(id).queryFirst();
		try {
			return yspTaskService.flowInit(tcwNeedPayAccountPay.getBid(), reason, ShiroUtils.getUserId());
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("服务器正在开小差，请联系客服");
		}
	}
	
	/**
	 * 删除
	 * @throws Exception 
	 */
	@PostMapping("/delete")
    @ResponseBody
	public R delete(Long id){
		
		try {
			return tcwNeedPayAccountPayService.deleteTrue(id);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error("操作失败，请联系客服");
		}
	}
	
	/*
	 * 导出
	 */
	@RequiresPermissions("tcwNeedPayAccountPay:export")
	@RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwNeedPayAccountPayItem cond) throws Exception{
		
		cond = setSeachSql(cond);
		
		cond.setOrderby("A.Id DESC");
		
		cond.setPage(0).setSize(999999);

		List<Map<String, Object>> listData = cond.queryMap();
        
    	List<YsCol> listField = new YsCol()
    			.setMenuId(MenuId.TCW_NeedPayAccountPay)
    			.setFrontShow(YsColEnum.FrontShow.SHOW.value)
    			.setOrderby("A.SortNo asc")
    			.queryList();
    	
        ExportExcelUtils<TcwNeedPayAccountPay> util = new ExportExcelUtils<TcwNeedPayAccountPay>(new TcwNeedPayAccountPay());
        
        String toFilePath = util.exportExcel(listData, listField, "应付账户支付");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
    }

    /*
     * 设置查询的cond的sql设置
     */
    public TcwNeedPayAccountPayItem setSeachSql(TcwNeedPayAccountPayItem cond){
		
		cond.addLeftJoin("TCW_NeedPayAccountPay B on B.Bid = A.Pbid")
			.addField("B.Bid bid")
			.addField("B.EffectStock effectStock")
			.addField("B.NeedPayAccountCode needPayAccountCode")
			.addField("B.CompanyBankInfoVid companyBankInfoVid");
		
		cond.addLeftJoin("TCW_NeedPayAccount B1 on B1.Code = B.NeedPayAccountCode")
			.addField("B1.Name needPayAccountName")
			.addField("B1.PartnerBankInfoVid partnerBankInfoVid");
		
		cond.addLeftJoin("TB_CompanyInfo B2 on B2.Vid = B1.CompanyVid")
			.addField("B2.Vname companyVname");
		
		cond.addLeftJoin("TCW_PartnerBankInfo B3 on B3.Vid = B1.PartnerBankInfoVid")
			.addField("B3.Vyhzhmc partnerBankInfoVyhzhmc")
			.addField("B3.Vkhh partnerBankInfoVkhh")
			.addField("B3.PartnerId partnerId")
			.addField("B3.PartnerName partnerName");
		
		cond.addLeftJoin("TS_UserChange C on C.Id = B.CreateChangeId")
			.addField("C.UserId createUserId");
		
		cond.addLeftJoin("TB_CompanyBankInfo D on D.Vid = B.CompanyBankInfoVid")
			.addField("D.Vyhzhmc companyBankInfoVyhzhmc")
			.addField("D.Vyhzh companyBankInfoVyhzh")
			.addField("D.Vkhh companyBankInfoVkhh");
		
		cond.addLeftJoin("TCW_NeedPayLedgerDetail E on E.Id = A.NeedPayLedgerDetailId")
			.addField("E.NeedPayTypeCode needPayTypeCode")
			.addField("E.Vjylx vjylx")
			.addField("E.DetailName detailName")
			.addField("E.CostPrice costPrice")
			.addField("E.Quantity quantity")
			.addField("(E.CostPrice * E.Quantity) totalPrice")
			.addField("E.ServicePrice servicePrice")
			.addField("E.PayedPrice payedPrice")
			.addField("E.ProxyPrice proxyPrice")
			.addField("(E.CostPrice * E.Quantity - E.PayedPrice) unpayPrice");
		
		cond.addLeftJoin("TB_NeedPayType E1 on E1.Code = E.NeedPayTypeCode")
			.addField("E1.Name needPayTypeName");
		
		cond.addLeftJoin("THR_OperateCompanyApply E2 on E2.Vgsbm = E.Vgsbm")
			.addField("E2.Vgsbm vgsbm")
			.addField("E2.Vgsjc vgsjc");
		
		cond.addLeftJoin("TCW_AccountCountForCompany E3 on E3.Vgsbm = E.Vgsbm")
			.addField("E3.Fje fje");
			
		cond.addLeftJoin("YS_ProcInst F on F.Bid = A.Pbid")
			.addField("F.UpdateTime auditTime");
        return  cond;
    }

	/**
	 * 弹出框
	 */
	@RequestMapping("/searchForModal")
	@ResponseBody
	public LayuiTableVoJA searchForModal(@ModelAttribute TcwNeedPayAccountPay cond){
		cond.setStatus(1);
		return commonApiService.searchLay(cond);
	}


	/**
	 * 打印 2024-10-15
	 * @param params
	 * @throws Exception
	 * @Author: fxz
	 */
	@RequestMapping("/exportdy")
	@ResponseBody
	public R exportdy(HttpServletRequest request,@RequestParam Map<String, Object> params) throws Exception{
		String bid = params.get("bid").toString();
		List<Map<String,Object>> infoList = new TcwNeedPayAccountPay()
				.addLeftJoin("TS_UserChange U ON U.Id = A.CreateChangeId ")
				.addField("U.UserId + '/' + U.UserName AS _ys_createUserName")//制单人
				.addField("U.DeptName AS deptName")//制单人部门
				.addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS createTimeByStr")//创建时间
				.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
				.addField("CASE WHEN P.UpdateTime IS NULL AND A.EffectStock = 1 THEN FORMAT(A.UpdateTime, 'yyyy-MM-dd HH:mm:ss') ELSE FORMAT(P.UpdateTime, 'yyyy-MM-dd HH:mm:ss') END auditingTime")//审核时间

				.addLeftJoin("TCW_NeedPayAccountPayItem EE on EE.Pbid = A.Bid")
				.addField("EE.amount")

				.addLeftJoin("TCW_NeedPayAccount B1 on B1.Code = A.NeedPayAccountCode")
				.addField("B1.Name needPayAccountName")
				.addField("B1.PartnerBankInfoVid partnerBankInfoVid")

				.addLeftJoin("TB_CompanyInfo B2 on B2.Vid = B1.CompanyVid")
				.addField("B2.Vname companyVname")

				.addLeftJoin("TCW_PartnerBankInfo B3 on B3.Vid = B1.PartnerBankInfoVid")
				.addField("B3.Vyhzhmc partnerBankInfoVyhzhmc")
				.addField("B3.Vyhzh partnerBankInfoVyhzh")
				.addField("B3.Vkhh partnerBankInfoVkhh")
				.addField("B3.PartnerId partnerId")
				.addField("B3.PartnerName partnerName")

				.addLeftJoin("TB_CompanyBankInfo D on D.Vid = A.CompanyBankInfoVid")
				.addField("D.Vyhzh companyBankInfoVyhzh")
				.addField("D.Vyhzhmc companyBankInfoVyhzhmc")
				.addField("D.Vyhzh companyBankInfoVyhzh")
				.addField("D.Vkhh companyBankInfoVkhh")

				.addLeftJoin("TCW_NeedPayLedgerDetail E on E.Id = EE.NeedPayLedgerDetailId")
				.addField("E.Vjylx vjylx")
				.setBid(bid)
				.queryMap();

		if(infoList!=null && infoList.size()>0){
			Map<String,Object> sonByOne = infoList.get(0);

			BigDecimal sonAmountTotal = BigDecimal.ZERO;
			String vjylx = sonByOne.get("vjylx").toString();
			for (Map<String, Object> son : infoList){
				sonAmountTotal = sonAmountTotal.add(new BigDecimal(son.get("amount").toString()));
			}

			String nameStrIn =  (sonByOne.get("partnerBankInfoVyhzhmc")!=null ? sonByOne.get("partnerBankInfoVyhzhmc").toString():"")
					+ "/" + (sonByOne.get("partnerBankInfoVyhzh")!=null ? sonByOne.get("partnerBankInfoVyhzh").toString():"")
					+ "/" + (sonByOne.get("partnerBankInfoVkhh")!=null ? sonByOne.get("partnerBankInfoVkhh").toString():"");

			List<NameValueDto> listData = new ArrayList<>();
			listData.add(new NameValueDto("单据编号",bid));
			listData.add(new NameValueDto("申请人",sonByOne.get("_ys_createUserName").toString()));
			listData.add(new NameValueDto("申请部门",sonByOne.get("deptName").toString()));
			listData.add(new NameValueDto("收款账号",nameStrIn));
			listData.add(new NameValueDto("付款类型",vjylx));
			listData.add(new NameValueDto("付款金额",sonAmountTotal.toString()));
			listData.add(new NameValueDto("付款说明",sonByOne.get("remark").toString()));
			String url = pdfService.generatePDF(bid,"应付账户支付单", sonByOne.get("companyVname").toString(), sonByOne.get("createTimeByStr").toString(),listData);
			return R.ok(url);
		}else {
			return R.error("未查询到要导出的数据");
		}


	}

}
